import { ref } from 'vue';
import api from '../api/api';

/**
 * 使用文章搜索逻辑
 */
export const useArticleSearch = () => {
  // 搜索参数
  const searchParams = ref({
    page: 1,
    pageSize: 10,
    title: '',
    content: '',
    begin: '',
    end: '',
    categoryId: '',
    userId: null,
    tags: null
  });

  // 搜索结果
  const searchResults = ref({
    articles: [],
    total: 0,
    page: 1,
    limit: 10,
    totalPages: 0
  });

  // 加载状态
  const loading = ref(false);

  // 错误信息
  const error = ref(null);

  /**
   * 提交搜索请求
   */
  const submitSearch = async () => {
    loading.value = true;
    error.value = null;

    try {
      const params = { ...searchParams.value };

      const response = await api.post('/articles/search', params);

      if (response.data.code === 1 && response.data.msg === 'success') {
        // 更新搜索结果
        searchResults.value.articles=response.data.data.rows;
        searchResults.value.total=response.data.data.total;
        searchResults.value.totalPages=response.data.data.totalPages;
        console.log('搜索结果:', searchResults.value);
        return searchResults.value;
      } else {
        throw new Error(response.data.msg || '搜索失败');
      }
    } catch (err) {
      console.error('请求出错:', err);
      error.value = err.message || '网络错误，请重试';
    } finally {
      loading.value = false;
    }
  };

  /**
   * 重置搜索表单
   */
  const resetForm = () => {
    searchParams.value = {
      page: 1,
      pageSize: 10,
      title: '',
      content: '',
      begin: '',
      end: '',
      categoryId: '',
      userId: null
    };
  };

  return {
    searchParams,
    searchResults,
    loading,
    error,
    submitSearch,
    resetForm
  };
};